import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'format'})
export class FormatPipe implements PipeTransform {
    transform(value: number): string{
        // console.log(value);
        if(value != undefined){
            // 先当正数处理
            // console.log(value);
            if(value == 0){
                return "0";
            }
            let neg:boolean;
            if(value < 0){
                neg = true;
                value = value * (-1);
            }else{
                neg = false;
            }
            value = parseFloat(value.toFixed(2));

            // 小数部分
            let num_fraction:number = value - parseInt(value.toString(), 0);
            let str_fraction:string = '';
            // console.log(num_fraction);
            if(num_fraction.toString().length >= 4){ // 0.xx
                // console.log('>=4');
                str_fraction = num_fraction.toString().slice(1,4);
            }else if(num_fraction.toString().length == 3){ // 0.x
                // console.log('=3');
                str_fraction = num_fraction.toString().slice(1,3) + '0';
            }else{ // 0
                // console.log('otherwise');
                str_fraction = '.00';
            }
            // console.log(str_fraction);

            // 整数部分
            value = parseInt(value.toString(), 0);
            var num = (value || 0).toString();
            var result = '';
            while (num.length > 3) {
                result = ',' + num.slice(-3) + result;
                num = num.slice(0, num.length - 3);
            }
            if (num) { result = num + result; }

            // 整数加小数
            // result = result + str_fraction;

            if(neg){
                result = '-' + result;
            }
        }

        // console.log(result);
        return result;
    }
}
